<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" icon="Plus" @click="addBranding">
        添加品牌
      </el-button>
      <el-table style="margin: 10px auto" border :data="dataBarding">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName" />
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              icon="Edit"
              @click="updateTradeMarkInfo(row)"
            ></el-button>

            <el-popconfirm
              :title="`Are you sure to delete ${row.tmName}?`"
              icon="Delete"
              @confirm="removeTrademark(row.id)"
            >
              <template #reference>
                <el-button type="primary" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="everyItem"
        :page-sizes="[3, 10, 20, 100]"
        :background="true"
        layout="prev, pager, next, jumper,->,total, sizes"
        :total="total"
        @current-change="getProduct"
        @size-change="getProduct(1)"
      />
    </el-card>
    <!-- v-model:控制显示于隐藏 -->
    <el-dialog
      v-model="DialogVisible"
      :title="tradeMarkParams.id ? '修改品牌' : '添加品牌'"
      width="50%"
    >
      <el-form
        style="width: 80%"
        label-width="80px"
        :model="tradeMarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="tradeMarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
          <!-- upload：action:请求URL -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="tradeMarkParams.logoUrl"
              :src="tradeMarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getProductInfo,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark/index'
import { Recodes, TradeMarkDate, tradeMark } from '@/api/product/trademark/type'
import { UploadProps, ElMessage } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'
// let reqPro = getProductInfo();
//  当前页码
let currentPage = ref<number>(1)
// 每页显示的条目数
let everyItem = ref<number>(3)
let DialogVisible = ref<boolean>(false)
// 收集新增品牌
let tradeMarkParams = reactive<tradeMark>({
  tmName: '',
  logoUrl: '',
})
let total = ref<number>()
let dataBarding = ref<Recodes>()
const getProduct = async (pager = 1) => {
  currentPage.value = pager
  let reqPro: TradeMarkDate = await getProductInfo(
    currentPage.value,
    everyItem.value,
  )
  console.log(reqPro)
  if (reqPro.code == 200) {
    total.value = reqPro.data.total
    dataBarding.value = reqPro.data.records
    console.log(dataBarding)
    ElMessage({
      type: 'success',
      message: '获取品牌成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '获取品牌失败',
    })
  }
}
let addBranding = () => {
  DialogVisible.value = true
  tradeMarkParams.id = 0
  tradeMarkParams.tmName = ''
  tradeMarkParams.logoUrl = ''
  // 杜绝undefine 有则清除，也可以使用nextTick
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
}
let cancel = () => {
  DialogVisible.value = false
}
// 确定按钮
const formRef = ref()
let confirm = async () => {
  console.log(formRef)
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(tradeMarkParams)
  console.log(result)
  if (result.code == 200) {
    DialogVisible.value = false
    ElMessage({
      type: 'success',
      message: tradeMarkParams.id ? '修改成功' : '添加成功',
    })
    getProduct(tradeMarkParams.id ? currentPage.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: tradeMarkParams.id ? '修改失败' : '添加失败',
    })
    DialogVisible.value = false
  }
}
onMounted(() => {
  getProduct()
})
// 上传图片之前触发的钩子函数
// rawFile当前上传的文件对象
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 约束类型和大小
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG/PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
// 图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  tradeMarkParams.logoUrl = URL.createObjectURL(uploadFile.raw!)
  formRef.value.clearValidate('logoUrl')
}
// 修改数据
const updateTradeMarkInfo = (row: any) => {
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
  DialogVisible.value = true
  Object.assign(tradeMarkParams, row)
  console.log(tradeMarkParams)
}
// 自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  console.log(rule)
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('请上传图片'))
  }
}
// 表单校验规则对象
const rules = {
  tmName: [
    {
      // 必须校验
      required: true,
      // 触发时机 blur and change
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      // 必须校验
      required: true,
      validator: validatorLogoUrl,
    },
  ],
}
// 删除
const removeTrademark = async (id: number) => {
  let result = await reqDeleteTrademark(id)
  console.log(result)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    getProduct(
      dataBarding.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
